package com.share.tool.m2d.kundb.tablestructure;

import com.share.common.utils.FileUtil;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class DbMain {
    public static Map<String, Map<String, String>> dbMap = new HashMap<>();

    public static void main(String[] args) {
        Db[] values = Db.values();
        for (Db item : values) {
            String name = item.getDbName();
            Map<String, String> map = dbMap.get(name);
            String filepath = item.getFilepath();
            if (new File(filepath).exists()) {
                exe(filepath, map);
            } else {
                System.out.println("sql结构文件不存在-" + filepath);
            }
        }
    }


    static {
        //读取配置
        String productConfigurePath = DbMain.class.getClassLoader().getResource("kundb\\kundb.txt").getPath();
        List<String> list = FileUtil.readByLine(productConfigurePath);
        Map<String, String> map = null;
        for (String tmp : list) {
            String line = tmp.trim();
            if (line.length() == 0) {
                continue;
            }

            if (Db.listDbName().contains(line)) {
                map = new HashMap<>();
                dbMap.put(line, map);
            } else {
                String[] split = line.split(",");
                if (split.length == 2) {
                    map.put(split[0].trim(), split[1].trim());
                } else if (split.length == 1) {
                    map.put(line, null);
                }
            }
        }
    }

    public static void exe(String tabelStructFile, Map<String, String> distrMap) {
        StringBuffer sb = new StringBuffer();
        List<String> midList = FileUtil.readByLine(tabelStructFile);
        List<String> list = filterHeader(midList);
        String tableName = null;
        TreeMap<Integer, String> keyMap = new TreeMap<>();
        for (String str : list) {
            String line = str.trim();
            if (line.length() == 0) {
//                sb.append("");
                continue;
            } else if (line.startsWith("--")) {
//                sb.append(line);
                continue;
            } else if (line.startsWith("/*")) {
//                sb.append("");
            } else if (line.startsWith("SET ")) {
//                sb.append("");
            } else if (line.startsWith("CREATE DATABASE")) {
//                sb.append("");
            } else if (line.startsWith("USE ")) {
//                sb.append("");
                continue;
            } else {
                if (line.startsWith("DROP")) {
                    tableName = null;
                    keyMap.clear();
                    continue;
                } else if (line.startsWith("CREATE")) {
                    tableName = line.replaceAll("CREATE", "").replaceAll("TABLE", "").replaceAll("IF", "").replaceAll("EXISTS", "").replaceAll(";", "").replaceAll("`", "").replaceAll("\\(", "").trim();
                    sb.append(System.lineSeparator());
                }

                if (distrMap.keySet().contains(tableName)) {
                    if (line.contains(")") && line.contains("ENGINE") && line.contains("=")) {
                        StringBuffer tmp = new StringBuffer(line);
                        tmp.deleteCharAt(tmp.length() - 1);
                        tmp.append(" DISTRIBUTED BY HASH(" + (distrMap.get(tableName) != null ? distrMap.get(tableName) : keyMap.get(keyMap.keySet().toArray(new Integer[10])[0])) + ") USING `binary_md5`;");
                        sb.append(tmp.toString());
                    } else if (line.startsWith("CREATE")) {
                        sb.append("DROP TABLE IF EXISTS " + tableName + ";");
                        sb.append(System.lineSeparator());

                        //加建表语句
                        sb.append(line);
                    } else {
                        sb.append(line);

                        //提取分片健
//                        if (line.contains("id_card")) {
//                            keyMap.put(3, "id_card");
//                        } else if (line.contains("phone_no")) {
//                            keyMap.put(5, "phone_no");
//                        } else {
//                            keyMap.put(7, "session_id");
//                        }

                        keyMap.put(7, "session_id");
                    }

                    //追加换行
                    sb.append(System.lineSeparator());
                } else {
                    //不是我要的表
                    tableName = null;
                    keyMap.clear();
                }
            }
        }

        FileUtil.write(tabelStructFile + "-分表.txt", sb.toString());
    }

    private static List<String> filterHeader(List<String> list) {
        int i = 0;
        int flag = 0;
        List<String> relist = list;
        for (String str : list) {
            i++;
            String line = str.trim();
            if (line.equals("/*")) {
                flag = flag + 1;
            } else if (str.trim().equals("*/")) {
                flag = flag + 1;
                break;
            }

            if (line.startsWith("SET ")) {
                break;
            } else if (line.startsWith("DROP")) {
                break;
            } else if (line.startsWith("CREATE DATABASE")) {
                break;
            } else if (line.startsWith("USE ")) {
                break;
            }

            if (i > 20) {
                break;
            }
        }
        if (flag == 2) {
            relist = list.subList(i, list.size());
        }
        return relist;
    }
}

